package li.com.ruiji.filter;

import com.alibaba.fastjson.JSON;
import li.com.ruiji.common.MyBaseContext;
import li.com.ruiji.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
// 表示这是一个拦截器，（拦截器名称，拦截哪些请求）
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Autowired
    private RedisTemplate redisTemplate;
//    工具类，可以判断两个字符串是否相同，支持通配符
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
//        1.获取拦截到的这个url
        String requestURI = request.getRequestURI();
//        2.判断这个url需不需要处理
//            不需要处理的请求
        String [] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        boolean check = check(urls, requestURI);
//        3.不需要处理则直接放行
        if (check){
            log.info("不需要处理");
            filterChain.doFilter(request,response);
            return;
        }
//        4-1.需要处理的判断是否登录(电脑端)
//        request.getSession().getAttribute()  获得Session中储存的数据
//
        if(request.getSession().getAttribute("employee")!=null){
            log.info("已登录");
            Long employee = (Long) request.getSession().getAttribute("employee");
            MyBaseContext.setLongId(employee);
            filterChain.doFilter(request,response);
            return;
        }
//        4-2.需要处理的判断是否登录(移动端)
//        request.getSession().getAttribute()  获得Session中储存的数据
        if(request.getSession().getAttribute("user")!=null){
            log.info("已登录");
            Long userId = (Long) request.getSession().getAttribute("user");
            MyBaseContext.setLongId(userId);
            filterChain.doFilter(request,response);
            return;
        }
//        5.未登录则返回未登录结果，通过输出流的方式向前端输出数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("未登录");
        return;

    }
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
//            判断两个字符串是否相同
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
